#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "linkedlist.h"
#include "fun.h"

//将文件中信息读取到链表中
GROUP * read_file_to_linked(GROUP * head)
{
        FILE * fp = NULL;
	GROUP * load = NULL;
	LXR * pload = NULL;
	char groupName[20], name[20], phoneNum[20];

	fp = fopen("./save", "r");
	assert(fp != NULL);
	while(!feof(fp))
	{
		memset(groupName, 0, sizeof(groupName));
		memset(name, 0, sizeof(name));
		memset(phoneNum, 0, sizeof(phoneNum));
		fscanf(fp, "%s", groupName);
		load = add_new_group(head, groupName);
		fscanf(fp, "%s", name);
		fscanf(fp, "%s", phoneNum);
		pload = add_new_people(load->h, name, phoneNum);
	}
	fclose(fp);
    
	return head;
}

//将链表中的数据保存到文件中
GROUP * save_linked_to_file(GROUP * head)
{
	FILE * fp = NULL;
	GROUP * load = head;
	LXR * pload = load->h;

	fp = fopen("./save", "w");
	assert(fp != NULL);
	while(load->next != NULL)
	{
		load = load->next;
		pload = load->h;
		while(pload->next != NULL)
		{
			pload = pload->next;
			fprintf(fp, "%s", load->groupName);
			fprintf(fp, "%c", ' ');
			fprintf(fp, "%s", pload->name);
			fprintf(fp, "%c", ' ');
			fprintf(fp, "%s", pload->phoneNum);
			if(load->next == NULL && pload->next == NULL)
			{
				break;
			}
			fprintf(fp, "%c", '\n');
		}	
	}
	fclose(fp);
    
	return head;
}